<?php
require_once('application/libraries/user.php');
class Registration extends MY_Controller{
    function __construct(){
    	parent::__construct();
    }
    function index(){
    	// If user is not logged in, show registration form, else redirect to first page
   		if($this->isLoggedIn() != TRUE){
    		$this->load->view('registrationForm');
    		$this->load->view('includes/footer');
    	}
    	else{
    		redirect('/');
    	}
    }

	function registerValidation(){
		// Load formvalidation-library
		$this->load->library('form_validation');
		// Set validation rules, all fields required, correct email and matching passwords
		$this->form_validation->set_rules(FIRSTNAME, 'First name', 'trim|required');
		$this->form_validation->set_rules(LASTNAME, 'Last  name', 'trim|required');
		$this->form_validation->set_rules(EMAIL, 'Email', 'trim|required|valid_email');
		$this->form_validation->set_rules(USERNAME, 'Username', 'trim|required|min_length[6]');
		$this->form_validation->set_rules(PASSWORD, 'Password', 'trim|required|min_length[6]|max_length[32]');
		$this->form_validation->set_rules(PASSWORD_CONFIRMATION, 'Password confirmation', 'trim|required|matches[password]');
		
		if($this->form_validation->run() == FALSE){
			// If input is not valid, reload registration page
			$this->index();
		}
		else{
			// If input is valid, create userobject and do registration
			$params = array(
				'id' => NULL, 
				'username' => $this->input->post(USERNAME),
				'firstname' => $this->input->post(FIRSTNAME),
				'lastname' => $this->input->post(LASTNAME),
				'password' => $this->input->post(PASSWORD),
				'email' => $this->input->post(EMAIL)
				);
			$user = new User($params);
			//var_dump($params);
			$this->load->model('registrationHandler');
			// skapa userobjekt och skicka in. 
			if($query = $this->registrationHandler->doRegistration($user)){
			echo "hjkhkj";
				// If registration is a success redirect to success-page and add successmessages
				$data['action'] = 'Your account is now registered.';
				$data['redirectLink'] = '/';
				$data['redirectText'] = 'Click here to log in.';
				$data['main_content'] = 'success';
				$this->load->view('includes/template', $data);
				
			}
			else{
			echo "hjkhkj";
				// If registration was not a success, reload page
				$this->index();
			}
		}
	}
}
